<script lang="ts" setup>
import type { CheckPlanApi } from '#/api';

import { computed, onUnmounted, ref, watch, watchEffect } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Button } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenForm } from '#/adapter/form';
import { addCheckPlan, EnumApi, updateCheckPlan } from '#/api';

import { useSchema } from './data';
import MachineryTab from './modules/machinery/MachineryTab.vue';
import SubjectTab from './modules/subject/Tab.vue';

const emit = defineEmits(['success']);
const formData = ref<CheckPlanApi.Row>();
const title = ref<string>();
const showConfrimBtn = ref(true);
const showTabs = ref(true);
const isSubmit = ref(false);

const planId = ref<null | number>();
const modelData = ref<Record<string, any>>();

/**
 * 初始化数据函数
 */
function initData() {
  planId.value = formData.value?.planId!;
}
const stopDataWatch = watchEffect(() => {
  modelData.value = {
    planId: planId.value,
    showButtons: formData.value?.attr1 === '2',
  };
});
onUnmounted(() => {
  stopDataWatch();
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    wrapperClass: 'grid-cols-4 gap-x-10 gap-y-4',
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: useSchema(),
  showDefaultActions: false,
  fieldMappingTime: [['rangePicker', ['startDate', 'endDate'], 'YYYY-MM-DD']],
});

const getTitle = computed(() => {
  if (formData.value?.attr1 === '1') return '查看计划';
  return formData.value?.attr1 === '2' ? '修改计划' : '添加计划';
});
const stopWatch = watch(getTitle, (newTitle) => {
  title.value = newTitle;
});
onUnmounted(() => {
  stopWatch();
});
const [Modal, modalApi] = useVbenModal({
  class: 'w-[90vw]',
  closeOnClickModal: true,
  destroyOnClose: true,
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      modalApi.lock();

      let data;
      await formApi.getValues().then((res) => {
        data = res;
      });
      // 判断是否点击的是提交按钮
      if (isSubmit.value) {
        data!.status = EnumApi.MesOrderStatusEnum.FINISHED;
      }
      try {
        await (formData.value?.planId
          ? updateCheckPlan(data!)
          : addCheckPlan(data!));
        modalApi.close();
        emit('success');
        resetForm();
      } finally {
        isSubmit.value = false;
        modalApi.lock(false);
      }
    }
  },
  onOpenChange(isOpen) {
    if (isOpen) {
      const data = modalApi.getData<CheckPlanApi.Row>();
      if (data) {
        // 修改为使用 dayjs 格式化日期字符串，避免类型不匹配问题
        if (data.startDate || data.endDate) {
          data.rangePicker = [
            dayjs(data.startDate) as any as Date,
            dayjs(data.endDate) as any as Date,
          ];
        }
        formData.value = data;
        initData();
        formApi.setValues(formData.value);
        showConfrimBtn.value = formData.value?.attr1 !== '1';
        modalApi.setState({
          showConfirmButton: showConfrimBtn.value,
        });
      }
    }
  },
});

function resetForm() {
  formApi.resetForm();
  formApi.setValues({});
}
function submitForm() {
  isSubmit.value = true;
  modalApi.onConfirm();
}
</script>

<template>
  <Modal :title="getTitle" :show-confirm-button="false">
    <Form class="mx-4" />

    <!-- Tabs表单 -->
    <el-tabs
      v-if="formData?.attr1"
      class="m-auto w-[75vw]"
      type="border-card"
      v-show="showTabs"
    >
      <el-tab-pane label="设备清单">
        <MachineryTab v-model="modelData" />
      </el-tab-pane>
      <el-tab-pane label="保养项目">
        <SubjectTab v-model="modelData" />
      </el-tab-pane>
    </el-tabs>

    <template #prepend-footer v-if="showConfrimBtn">
      <div class="flex flex-auto justify-between" v-if="showConfrimBtn">
        <!-- 左侧对齐Button -->
        <div>
          <Button
            v-if="!formData?.attr1"
            type="primary"
            danger
            @click="resetForm"
          >
            重置
          </Button>
        </div>
        <div class="flex gap-2">
          <Button type="primary" @click="modalApi.onConfirm"> 保存 </Button>
          <Button
            type="primary"
            class="bg-[#67c23a] hover:!bg-[#a3db87]"
            @click="submitForm"
          >
            提交
          </Button>
        </div>
      </div>
    </template>
  </Modal>
</template>
